package com.xinqi.common.mybatis;

import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.fasterxml.jackson.databind.JsonNode;
import com.xinqi.common.base.constants.C;
import com.xinqi.common.base.current.Currents;
import com.xinqi.common.base.user.Account;
import com.xinqi.common.mybatis.config.BaseMetaObjectHandler;
import com.xinqi.common.mybatis.config.CurrentUser;
import com.xinqi.common.mybatis.injector.ExtSqlInjector;
import com.xinqi.common.mybatis.type.JsonNodeTypeHandler;
import me.ahoo.cosid.IdGenerator;
import me.ahoo.cosid.provider.DefaultIdGeneratorProvider;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.Optional;

/**
 * mybatis-plus config
 *
 * <p>
 *
 * @author linkai
 * @MapperScan 注解添加扫描路劲
 *
 * <p>
 * 配置文档：http://mp.baomidou.com
 * @date 2022/11/25
 */
@AutoConfiguration(before = MybatisPlusAutoConfiguration.class)
@EnableTransactionManagement(proxyTargetClass = true)
public class MybatisPlusConfig {

    @Bean
    @ConditionalOnMissingBean(CurrentUser.class)
    public CurrentUser defaultCurrentUser() {
        return () -> Optional.of(
            Optional.ofNullable(Currents.get(Account.class)).map(Account::getId).orElse(C.DEFAULT_USER_ID)
        );
    }

    @Bean
    public ISqlInjector extSqlInjector() {
        return new ExtSqlInjector();
    }

    @Bean
    @ConditionalOnMissingBean(MetaObjectHandler.class)
    public MetaObjectHandler metaObjectHandler(ObjectProvider<CurrentUser> currentUser) {
        return new BaseMetaObjectHandler(currentUser);
    }

    @Bean
    public ConfigurationCustomizer customConfigurationCustomizer() {
        return configuration -> configuration.getTypeHandlerRegistry().register(JsonNode.class,
            new JsonNodeTypeHandler());
    }

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 分页插件
        interceptor.addInnerInterceptor(paginationInnerInterceptor());
        // 乐观锁插件
        interceptor.addInnerInterceptor(optimisticLockerInnerInterceptor());
        return interceptor;
    }

    /**
     * 分页插件，自动识别数据库类型
     */
    public PaginationInnerInterceptor paginationInnerInterceptor() {
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
        // 设置最大单页限制数量，默认 500 条，-1 不受限制
        paginationInnerInterceptor.setMaxLimit(-1L);
        // 分页合理化
        paginationInnerInterceptor.setOverflow(false);
        return paginationInnerInterceptor;
    }

    /**
     * 乐观锁插件
     */
    public OptimisticLockerInnerInterceptor optimisticLockerInnerInterceptor() {
        return new OptimisticLockerInnerInterceptor();
    }

    /**
     * 使用网卡信息绑定雪花生成器
     * 防止集群雪花ID重复
     */
    @Bean
    public IdentifierGenerator idGenerator() {
        return new CosidIdentifierGenerator();
    }

    public static class CosidIdentifierGenerator implements IdentifierGenerator {
        @Override
        public Number nextId(Object entity) {
            IdGenerator share = DefaultIdGeneratorProvider.INSTANCE.getShare();
            return share.generate();
        }
    }

}

